package com.lfk.three.con;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;

import com.lfk.three.static_info.static_info;
import com.lfk.three.utils.logger.Logger;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;

/**
 * Created by liufengkai on 16/4/9.
 */
public class UpLoadQueue {
    private Handler handler;

    private class MsgThread extends HandlerThread {

        public MsgThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            super.run();
        }
    }

    private static UpLoadQueue mInstance = null;

    private MsgThread thread;

    public UpLoadQueue() {
        thread = new MsgThread("msg_queue");
        thread.start();
        handler = new Handler(thread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case static_info.UPLOAD_PIC:
                        upload(msg.obj.toString());
                        break;
                }
            }
        };
    }

    public static UpLoadQueue getInstance() {
        if (mInstance == null) {
            synchronized (UpLoadQueue.class) {
                if (mInstance == null)
                    mInstance = new UpLoadQueue();
            }
        }
        return mInstance;
    }

    private String upload(String FilePath) {
        Logger.d(FilePath);
        UploadManager uploadManager = new UploadManager();
        try {
            //调用put方法上传
            Response res = uploadManager.put(FilePath, null, static_info.getToken());
            //打印返回的信息
            return res.toString();
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            return r.toString();
        }
    }

    public void uploadImg(String FilePath) {
        Message msg = handler.obtainMessage();
        msg.what = static_info.UPLOAD_PIC;
        msg.obj = FilePath;
        handler.sendMessage(msg);
    }


}
